package com.fubowen.reader.extension

import android.content.Context
import android.graphics.drawable.ClipDrawable
import android.graphics.drawable.GradientDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.core.view.children

val View.RADIUS_SM get() = dpToPx(4)
val View.PADDING_SM get() = dpToPx(4)
val View.PADDING_MD get() = dpToPx(8)
val View.PADDING_LG get() = dpToPx(12)
val View.PADDING_XL get() = dpToPx(16)
val View.STROKE_SM get() = dpToPx(1)
fun View.setVisible(isVisible: Boolean) {
    this.visibility = if (isVisible) View.VISIBLE else View.GONE
}

fun View.dpToPxFloat(dp: Int) = context.dpToPxFloat(dp)
fun View.dpToPx(dp: Int) = context.dpToPx(dp)
fun View.setClipDrawable(progress: Int, color: Int, radius: Int = RADIUS_SM) {
    if (background is ClipDrawable) {
        background.level = progress * 100
    } else {
        ClipDrawable(createRadiusRectDrawable(color, radius), Gravity.START, ClipDrawable.HORIZONTAL).apply {
            level = progress * 100
            background = this
        }
    }
}

fun View.setRadiusRectDrawable(strokeColor: Int, radius: Int = RADIUS_SM, strokeWidth: Int = STROKE_SM) {
    GradientDrawable().apply {
        shape = GradientDrawable.RECTANGLE
        cornerRadius = radius.toFloat()
        setStroke(strokeWidth, strokeColor)
        background = this
    }
}

fun View.createRadiusRectDrawable(color: Int, radius: Int) = GradientDrawable().apply {
    shape = GradientDrawable.RECTANGLE
    cornerRadius = radius.toFloat()
    setColor(color)
}

fun Context.createPopupWindow(onCreateView: (LayoutInflater, PopupWindow) -> View) = lazy {
    val inflater = LayoutInflater.from(this)
    PopupWindow().apply {
        width = ViewGroup.LayoutParams.MATCH_PARENT
        height = ViewGroup.LayoutParams.WRAP_CONTENT
        isTouchable = true
        elevation = 10f
        contentView = onCreateView(inflater, this)
    }
}
fun View.setShapeColor(color: Int, shape: Int = GradientDrawable.RECTANGLE, radius: Int = 8) {
    val shapeDrawable = GradientDrawable()
    shapeDrawable.shape = shape
    shapeDrawable.cornerRadius = dpToPx(radius).toFloat()
    shapeDrawable.setColor(color)
    this.background = shapeDrawable
}

